package gw.com.android.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.gwtsz.gts2.hx.R;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.bulletin.BulletinDetailActivity;
import gw.com.android.ui.bulletin.NotifyRequest;
import gw.com.android.ui.dialog.BaseDialog;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.app.ObjectSessionStore;
import www.com.library.dialog.BasePopWindow;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.util.DoubleConverter;
import www.com.library.view.LoadingDialog;

/**
 * Created by reeta.zou on 2016/11/29.
 * 消息推送处理类
 */
public class MessageReceiver extends BroadcastReceiver {

    private Context mContext;
    private String mCustomContent;
    private String title;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        Bundle bundle = intent.getExtras();
        Logger.e("[MyReceiver] onReceive - " + intent.getAction());
        if (bundle == null) {
            return;
        }

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Logger.e("[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Logger.e("[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            mCustomContent = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Logger.e("[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId + ", " + mCustomContent);
            processMessage();
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            if (AppMain.isAppRun()) {
                mCustomContent = bundle.getString(JPushInterface.EXTRA_EXTRA);
                title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
                Logger.e("[MyReceiver] 用户点击打开了通知: " + mCustomContent + "...title:" + title);
                clickNotification();
            }

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Logger.e("[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Logger.e("[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Logger.e("[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    /**
     * 消息处理
     */
    private void processMessage() {
        if (mCustomContent != null && mCustomContent.length() > 1) {
            Logger.i("_notify", "received a message and processMessage");
            new NotifyRequest().getNoticeList(GTConfig.instance().mCurName, null);
        }

    }

    /**
     * 发送通知
     */
    public void clickNotification() {
        if (mCustomContent != null && mCustomContent.length() > 1) {
            try {
                MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
                if (null != mainActivity && !mainActivity.isFinishing()) {
                    if (null != LoadingDialog.instance()) {
                        LoadingDialog.instance().dismiss();
                    }
                    if (null != BaseDialog.instance()) {
                        BaseDialog.instance().dismiss();
                    }
                    if (null != BasePopWindow.instance()) {
                        BasePopWindow.instance().hidden();
                    }
                }
                Logger.e("推送消息：" + mCustomContent);
                JSONObject obj = new JSONObject(mCustomContent);
                // key1为前台配置的key
                String language = GTConfig.LANG_ZH_CN;
                if (!obj.isNull("lang")) {
                    language = obj.getString("lang");
                }

                String contenttype2 = AppContances.BULLENTIN_TYPE_IMPORTANT + "";

                String mDataId = "";
                //用来判读是否使用新的openApiPush
                boolean isOpenApiPush = false;
                String extend = "";
                if (!obj.isNull("dataid")) {
                    mDataId = obj.getString("dataid");
                } else {
                    isOpenApiPush = true;
                    mDataId = String.valueOf(obj.getInt("id"));
                    extend = obj.getString("extend");
                }

                //处理具体点击事件
                processCustomMessage(DoubleConverter.toIntData(mDataId), contenttype2, language, isOpenApiPush, extend);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 处理具体点击事件
     */
    private void processCustomMessage(int dataid, String contenttype2, String language, boolean isOpenApiPush, String extend) {
        GTConfig.instance().hasNotify = true;
        Activity currentActivity = AppActivities.getSingleton().currentActivity();
        if (currentActivity != null) {
            if (isOpenApiPush) {
                ActivityManager.showBulletinDetailActivityOpenApi(currentActivity, AppMain.getAppString(R.string.system_notice_detail), String.valueOf(dataid), contenttype2, language, title, extend);
            } else {
                ActivityManager.showBulletinDetailActivity(currentActivity, AppMain.getAppString(R.string.system_notice_detail), dataid, contenttype2, language, title);
            }
            if (currentActivity instanceof BulletinDetailActivity) {
                currentActivity.finish();
            }

        } else {
            try {
                Logger.e("从通知栏启动应用程序。。。");
                Intent intent = mContext.getPackageManager().
                        getLaunchIntentForPackage(AppMain.getApp().getPackageName());
                intent.setFlags(
                        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                //未开启应用处理
                intent.putExtra("where", AppContances.TYPE_FORM_NOTIFY);
                if (ConfigUtil.instance().homeFucType() != 0) {
                    intent.putExtra("mCurTag", ConfigType.TAB_HOME_TAG);
                } else {
                    intent.putExtra("mCurTag", ConfigType.TAB_QUOTE_TAG);
                }
                intent.putExtra("title", title);
                intent.putExtra("mDataId", dataid);
                intent.putExtra("type", contenttype2);
                intent.putExtra("language", language);
                intent.putExtra("isOpenApiPush", isOpenApiPush);
                mContext.startActivity(intent);
            } catch (Exception e) {
                //Toast.makeText(mContext, "没有安装", Toast.LENGTH_LONG).show();
                new ToastPopWindow(mContext, "没有安装", Toast.LENGTH_LONG).show();
            }
        }
    }

}
